use strict;
use warnings;

use JSON;
use IO::Socket;

my $socket;
my $client_name = 'odch';

sub execute {
	my $method = shift;
	my $args = shift;
	no strict 'refs';
	if (defined &{"odch::$method"}) {;
		"odch::$method"->(@$args);
	}
}

sub main {
	my $i = 0;
	while (not $socket) {
		print "attempting to establish internal comms\n";
		$socket = IO::Socket::INET->new('localhost:9003');
		if ($socket) {
			print "connected!\n";
			my $message = encode_json({ type => 'register_outgoing', name => $client_name}) . "\n";
			print "MESSAGE: $message";
			print $socket $message;
			last;
		}

		if (++$i > 10) {
			print "tried ten times, giving up\n";
			exit;
		}
		sleep 5;
	}

	print "entering listening loop\n";

	while (my $data = <$socket>) {
		if (not $socket) {
			print "Problem with socket, exiting\n";
			last;
		}

		if (not $data =~ /^\s*$/) {
			print "got data: $data\n";
			my $message = decode_json($data);

			my $method = $message->[0];
			my $args = $message->[1];

			execute($method, $args);
		}
	}
}

